package pers.vic.basics.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @description: 56. 合并区间 {@literal https://leetcode-cn.com/problems/merge-intervals/ }
 * @see J0057_H_Insert 扩展应用
 * @author Vic.xu
 * @date: 2020/12/17 0017 8:28
 */
public class J0056_M_Merge {
    /*
    给出一个区间的集合，请合并所有重叠的区间。
     */

    public static int[][] merge(int[][] intervals) {
        if (intervals.length == 0) {
            return new int[0][0];
        }
        List<int[]> list = new ArrayList<>();
        //先按照区间的首位 升序排列
        Arrays.sort(intervals, (a,b)->{
            return Integer.signum(a[0] - b[0]);
        });
        int[] temp = intervals[0];
        list.add(temp);

        for (int i = 1; i < intervals.length; i++) {
            int[] cur = intervals[i];
            //合并
            if (cur[0]<= temp[1]) {
                //可能被全包含
                temp[1] = Math.max(cur[1], temp[1]);
            }else {
                //不合并
                temp = cur;
                list.add(temp);
            }
        }
        return list.toArray(new int[0][0]);
    }

    public static void main(String[] args) {
        /*
        输入: intervals = [[1,3],[2,6],[8,10],[15,18]]
        输出: [[1,6],[8,10],[15,18]]
        解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].

        输入: intervals = [[1,4],[4,5]]
        输出: [[1,5]]
        解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。
         */
        int[][] intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};
        int[][] merge = merge(intervals);
        for (int[] ints : merge) {
            System.out.println(Arrays.toString(ints));
        }
        int[][] intervals2 = {{1, 4}, {2, 3}};
        int[][] merge2 = merge(intervals2);
        for (int[] ints : merge2) {
            System.out.println(Arrays.toString(ints));
        }
    }
}
